﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyFSMSystem  {

    private List<IEnemyState> m_states = new List<IEnemyState>(); //所有状态的集合


    private IEnemyState m_currentState; //当前状态
    public IEnemyState currentState { get { return m_currentState; } }


    /// <summary>
    /// 多个状态 同时添加到状态集合中
    /// </summary>
    /// <param name="states"></param>
    public void AddState(params IEnemyState[] states)
    {
        if (states == null || states.Length == 0)
        {
            Debug.LogError("IEnemyStates NULL");
            return;
        }
        foreach (IEnemyState s in states)
        {
            m_states.Add(s);
        }
    }


    /// <summary>
    /// 单个状态 增加状态到集合中
    /// </summary>
    /// <param name="state"></param>
    public void AddState(IEnemyState state)
    {
        if (state == null)
        {
            Debug.LogError(" Null Enemy State"); return;
        }
        if (m_states.Count == 0)
        {
            m_states.Add(state);
            m_currentState = state;
            m_currentState.DoBeforeEntering();
        }
        foreach (IEnemyState thestate in m_states)
        {
            if (thestate == state)
            {
                Debug.LogError("Already has " + state.GetStateID.ToString()); return;
            }
        }
        m_states.Add(state);
    }


    /// <summary>
    /// 从集合中删除某个状态
    /// </summary>
    /// <param name="state"></param>
    public void DeleteState(IEnemyState state)
    {
        if (state == null)
        {
            Debug.LogError("NULL Enemy STATE "); return;
        }
        foreach (IEnemyState theEnemystate in m_states)
        {
            if (state == theEnemystate)
            {
                m_states.Remove(state); return;
            }
        }
        Debug.LogError("do not exist in List");
    }

    /// <summary>
    /// 执行状态转换
    /// </summary>
    /// <param name="transition"></param>
    public void PerformTransition(EnemyTransition transition)
    {
        if (transition == EnemyTransition.NullTransition)
        {
            Debug.LogError("Null transtion"); return;
        }
        EnemyStateID nextStateID = m_currentState.GetStateIDFromTransition(transition);
        if (nextStateID == EnemyStateID.NullStateID)
        {
            Debug.LogError("DO NOT EXIST THIS TRANSITION IN THIS STATE"); return;
        }
        foreach (IEnemyState state in m_states)
        {
            if (state.GetStateID == nextStateID)
            {
                m_currentState.DoBeforeLeaving();
                m_currentState = state;
                m_currentState.DoBeforeEntering();
                return;
            }
        }
        Debug.LogError("DO NOT EXIST THE STATE WITH THIS STATE ID");

    }
}
